package com.gregbugaj.nscaffold.util;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringWriter;

public class FileUtil {

	/**
	 * 
	 * @return path of where this application is running from
	 */
	public static String applicationPath(){
		File appPath = new File(FileUtil.class.getCanonicalName());		
		try
		{
			appPath = appPath.getCanonicalFile().getParentFile();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		return appPath.toString();
	}

	/**
	 * Create backup of a file with given extension
	 * @param fileToBackup
	 * @param ext Extension to use
	 */
	public static boolean createBackup(String fileToBackup, String ext) {		
		try{
			ext=ext==null?"bak":ext;
			File file=new File(fileToBackup);
			String backupFile=file.getParent()+ File.separator+file.getName().split("\\.")[0] + "." + ext;

			InputStream fin = new FileInputStream(fileToBackup);
			OutputStream fos = new FileOutputStream(new File(backupFile));
			int c;
			while ((c = fin.read()) >= 0) {
				fos.write(c);
			}
			fos.close();
			fin.close();

			return true;
		}catch(Exception e){
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * Get contents of a file as a string
	 * @param path of file to read
	 * @return string content of a file
	 */
	public static String getContent(String path) {
		StringWriter writer=new StringWriter();
		try {
			BufferedReader st = new BufferedReader(new FileReader(new File(path)));
			int c=0;
			while ((c = st.read()) >= 0) {
				writer.write(c);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return writer.toString();
	}

}
